/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cart.hibernate.rating;

/**
 *
 * @author BibooChung
 */

import cart.hibernate.HibernateUtil;
import java.util.List; 
import java.util.Iterator; 
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageRating {
    public List getAllRating() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        List allRating = null;
        try{
           tx = session.beginTransaction();
           allRating = session.createQuery("FROM Rating").list(); 
           tx.commit();
        }catch (HibernateException e) {
           if (tx!=null) tx.rollback();
           e.printStackTrace(); 
        }finally {
           session.close(); 
        }
        return allRating;
    }
    
    public long addRating(double avgRate, long numOfRate) { 
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        long rateId = -1;

        try {
            tx = session.beginTransaction();
            Rating rate = new Rating(avgRate, numOfRate);
            rateId = (Long) session.save(rate);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return rateId;
    }
    
    public void updateRating(long rateId, double newAvgRate, long newNumOfRate) {
        Session session = HibernateUtil.getSessionFactory().openSession();
    	Transaction tx = null;
    	try{
    	   tx = session.beginTransaction();
    	   Rating rate = (Rating)session.get(Rating.class, rateId); 
    	   rate.setRating(newAvgRate, newNumOfRate);
           session.update(rate);
    	   tx.commit();
    	}catch (HibernateException e) {
    	   if (tx!=null) tx.rollback();
    	   e.printStackTrace(); 
    	}finally {
    	   session.close(); 
    	}
    }

    public void deleteRating(long rateId) {
    	Session session = HibernateUtil.getSessionFactory().openSession();
    	Transaction tx = null;
    	try{
    	   tx = session.beginTransaction();
    	   Rating rate = (Rating)session.get(Rating.class, rateId); 
    	   session.delete(rate); 
    	   tx.commit();
    	}catch (HibernateException e) {
    	   if (tx!=null) tx.rollback();
    	   e.printStackTrace(); 
    	}finally {
    	   session.close(); 
    	}
    }
}
